<template>
  <div class="app-container">
    <page-panel-new class="mainListPanel">
      <el-row class="mbBottom">
        <el-col :span="16">
          <el-button type="primary" @click="doAdd('form1')"> 新增 </el-button>
        </el-col>
      </el-row>
      <el-table ref="table-main" :data="zbdata" height="300px" :loading="bgLoading" border>
        <el-table-column label="序号" type="index" width="50" align="center" />
        <!-- 检定周期,检定性质,检定日期,有效期至,证书编号,检定单位 -->
        <el-table-column label="检定周期" align="center" prop="jdzq" width="150" show-overflow-tooltip />
        <el-table-column label="检定性质" align="center" prop="jdxz" width="150" show-overflow-tooltip />
        <el-table-column label="检定日期" align="center" prop="jdrq" width="180" show-overflow-tooltip />
        <el-table-column label="有效期至" align="center" prop="yxqz" width="180" show-overflow-tooltip />
        <el-table-column label="证书编号" align="center" prop="zsbh" width="200" show-overflow-tooltip />
        <el-table-column label="检定单位" align="center" prop="jddw" width="200" show-overflow-tooltip />
         <el-table-column label="查看文档" align="center" class-name="small-padding">
          <template slot-scope="scope">
            <span v-if="scope.row.fileid && scope.row.classid && scope.row.filename"
              @click.stop="$bgxzfj({ classid: scope.row.classid, fileid: scope.row.fileid }, popjklj)">
              <el-link href="#" type="primary">{{ scope.row.filename }}</el-link>
            </span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" class="delbutton" @click="doUpdate(scope.row, scope.$index)"> 修改 </el-button>
            <el-button type="text" class="delbutton" @click="doDelete(scope.row, scope.$index)"> 删除 </el-button>
            <el-button type="text" @click="doView(scope.row, scope.$index)"> 查看 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <qjfy :total='total' @fun="qjfyfun"></qjfy>
    </page-panel-new>
    <el-dialog :title="dialogTitle" :visible.sync="Open1" class="qjztk" append-to-body>
      <div class="el-dialog-div">
        <el-form ref="form1" :model="formData" :validate-on-rule-change=false label-width="150px"
          :disabled="formDisable">
          <!-- 基本信息 -->
          <el-form-item label="检定周期" prop="jdzq" :rules="[
            { required: true, message: '请输入检定周期', trigger: 'blur' }
          ]">
            <el-input v-model="formData.jdzq" />
          </el-form-item>
          <el-form-item label="检定性质" prop="jdxz" :rules="[
            { required: true, message: '请输入检定性质', trigger: 'blur' }
          ]">
            <el-select filterable allow-create default-first-option placeholder="请选择" v-model="formData.jdxz">
              <el-option v-for="({ sjxdm, sjxmc }, index) in xlsj1" :key="index" :label="sjxmc" :value="sjxdm"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="检定日期" prop="jdrq" :rules="[
            { required: true, message: '请输入检定日期', trigger: 'blur' }
          ]">
            <el-date-picker v-model="formData.jdrq" type="date" placeholder="选择检定日期" />
          </el-form-item>
          <el-form-item label="有效期至" >
            <el-date-picker v-model="formData.yxqz" type="date" placeholder="选择有效期至" />
          </el-form-item>
          <el-form-item label="证书编号"  >
            <el-input v-model="formData.zsbh" />
          </el-form-item>
          <el-form-item label="检定单位"  >
            <el-select  filterable allow-create default-first-option placeholder="请选择" v-model="formData.jddw">
              <el-option v-for="({ sjxdm, sjxmc }, index) in xlsj2" :key="index" :label="sjxmc" :value="sjxdm"></el-option>
            </el-select>
          </el-form-item>
          <div v-if="!formDisable">
            <el-form-item class="wenddd" label="该设备用于检测的参数">
              <el-upload ref="upload" :limit="1" action="" :auto-upload="false" drag :file-list="dgfjwj.uploadFiles"
                name="upfile" :on-change="handleUploadChange_d" :on-remove="handleUploadRemove_d"
                :before-remove="handleUploadBeforeRemove_d">
                <i class="el-icon-upload" />
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              </el-upload>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="!formDisable" type="primary" @click="doSubmit"> 保存 </el-button>
        <el-button class="cancelBtn" @click="doClose"> 关 闭 </el-button>
      </div>
    </el-dialog>
    <qjckfj ref="ckfj"></qjckfj>

  </div>
</template>
<script lang="ts">
import Vue from 'vue'

import dayjs from 'dayjs'



export default Vue.extend({
  name: 'Sbgl-sbjdjz-yqsbjd',
  props: {
    // 父组件传递过来的参数
    popobj: {
      type: Object,
      default: () => ({})
    },
    popjklj: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      title: '', //页面标题
      dialogTitle: '', // 弹框标题
      bgLoading: false, // 表格加载状态
      Open1: false, //弹框状态
      // 查看详细信息,查看检定证书,使用单位,使用场所,保管地点,管理标识编号,检定标识编号,仪器设备名称,规格型号,自编号,生产厂家,
      // 出厂编号,使用人,购置日期,ABC分类,质量检测,工艺控制, 能源计量,产能计量,劳动防护,强检,
      // 工艺控制,能源计量,产能计量,劳动防护,强检,检定周期(月,检定日期,检定单位,测量介质,测量范围,准确度等级,准确度,检定性质,
      // 有效期至,证书编号,设备状态,资产属性,资产编号,大设备编号,备注
      zbdata: [

      ], //主表格数据
      xlsj1: [],//查询选择器 下拉数据
      xlsj2: [],//查询选择器 下拉数据
      xlsj3: [],//查询选择器 下拉数据
      xlsj4: [],//查询选择器 下拉数据
      xlsj5: [],//查询选择器 下拉数据
      xlsj6: [],//查询选择器 下拉数据
      xlsj7: [],//查询选择器 下拉数据
      xlsj8: [],//查询选择器 下拉数据
      xlsj9: [],//查询选择器 下拉数据

      formData: {
        id: '',

        "jdzq": "", // 检定周期
        "jdxz": "", // 检定性质
        "jdrq": "", // 检定日期
        "yxqz": "", // 有效期至
        "zsbh": "", // 证书编号
        "jddw": "" // 检定单位
      }
      , //录入Form数据
      formDisable: false, //表单禁用状态
      queryParams: {
        page: 1,           // 当前页数
        start: 0,           // 分页起始位置 (unchanged)
        limit: 50,          // 每页显示条数 (unchanged)
      },
      total: 0,
      dgfjwj: {  //上传配置
        uploadFiles: [], //已上传文件列表
      },
      hdfjwj: {  //上传配置
        uploadFiles: [], //已上传文件列表
      }

    }
  },
  computed: {
  },
  watch: {
    optype: {
      handler(newVal, oldVal) {
        if (newVal == 'ck') {
          this.formDisable = true;
        } else {
          this.formDisable = false;
        }
      },
      deep: true,
    },
    queryParams: {
      handler(newVal, oldVal) {
        this.getxlsj1();
      },
      deep: true,
    },
    // 第一就触发

    popobj: {
      handler(newVal, oldVal) {
        this.getListData(newVal);
      },
      deep: true,
    },
  },
  mounted() {
    this.getListData();
    this.getxlsj1();
  },
  methods: {
    //获取 选择器数据
    getxlsj1() {
      try {
        const param = {};
        this.$getSelectorData("in_jdxz", param, this.popjklj).then((res) => {  // 检定性质
          this.xlsj1 = res.success ? res.rows : [];
        })
        this.$getSelectorData("in_jddw", param, this.popjklj).then((res) => {  // 检定性质
          this.xlsj2 = res.success ? res.rows : [];
        })
      } catch (error) {
        console.warn('接口提示', error)
      }
    },
    //查询参数重置按钮事件
    resetQuery() {
      this.queryParams = {
        start: 1,         // 分页起始位置
        limit: 20,        // 每页显示条数
      };
      this.getListData()
    },
    czcxfun() {
      this.keycz++
      this.formData = {
        id: '',
        "jdzq": "", // 检定周期
        "jdxz": "", // 检定性质
        "jdrq": "", // 检定日期
        "yxqz": "", // 有效期至
        "zsbh": "", // 证书编号
        "jddw": "" // 检定单位
      }
    },
    qjfyfun(e) {//分页
      this.queryParams.start = e.start;
      this.queryParams.limit = e.limit;
    },

    handleUploadChange_d(file, filelist) { //上传文件改变事件
      var _fileData = new FormData();
      _fileData.append("bizPath", "syfxxt/khfw");
      _fileData.append("uploadType", "minio");
      _fileData.append("file", file.raw, file.name);
      this.$uploadFile(_fileData).then((res) => {
        if (res.data.code === 200) {
          file.minioID = res.data.data.split(":")[0];
          file.filename = file.name;
          this.dgfjwj.uploadFiles = filelist;
        } else {
          this.$message.error({ content: '上传失败!', placement: 'center' })
          filelist.splice(filelist.indexOf(file), 1);
          this.dgfjwj.uploadFiles = filelist;
        }
      })
        .catch(() => {
          this.$message.error({ content: '上传失败!', placement: 'center' });
          filelist.splice(filelist.indexOf(file), 1);
          this.dgfjwj.uploadFiles = filelist;
        });
    },
    handleUploadChange_h(file, filelist) {
      var _fileData = new FormData();
      _fileData.append("bizPath", "syfxxt/khfw");
      _fileData.append("uploadType", "minio");
      _fileData.append("file", file.raw, file.name);
      this.$uploadFile(_fileData).then((res) => {
        if (res.data.code === 200) {
          file.minioID = res.data.data.split(":")[0];
          file.filename = file.name;
          this.hdfjwj.uploadFiles = filelist;
        } else {
          this.$message.error({ content: '上传失败!', placement: 'center' })
          filelist.splice(filelist.indexOf(file), 1);
          this.hdfjwj.uploadFiles = filelist;
        }
      })
        .catch(() => {
          this.$message.error({ content: '上传失败!', placement: 'center' });
          filelist.splice(filelist.indexOf(file), 1);
          this.hdfjwj.uploadFiles = filelist;
        });
    },
    handleUploadBeforeRemove_d(file) {//上传文件删除前事件
      if (file.fileid && file.fjid) {
        return this.$modal.confirm("该文件已上传，确认删除该文件？");
      } else {
        return true;
      }
    },
    handleUploadBeforeRemove_h(file, filelist) {
      if (file.fileid && file.fjid) {
        return this.$modal.confirm("该文件已上传，确认删除该文件？");
      } else {
        return true;
      }
    },
    handleUploadRemove_d(file, filelist) {//上传文件删除事件
      this.dgfjwj.uploadFiles = filelist;
      if (file.fileid && file.id) {
        this.$submit_delfile({ fileid: file.fileid, id: file.id }, this.popjklj)
          .then((res) => {
            if (res.success) {
              this.$message.success({ content: '删除成功!', placement: 'center' })
            } else {
              this.$message.error({ content: '删除失败!', placement: 'center' })
            }
          })
          .catch(() => {
            this.$message.error({ content: '删除失败!', placement: 'center' })
          });
      }
    },
    handleUploadRemove_h(file, filelist) {
      this.hdfjwj.uploadFiles = filelist;
      if (file.fileid && file.fjid) {
        this.$submit_delfile_fj({ fileid: file.fileid, fjid: file.fjid, tzggid: this.formData.id }, this.popjklj)
          .then((res) => {
            if (res.success) {
              this.$message.success({ content: '删除成功!', placement: 'center' })
            } else {
              this.$message.error({ content: '删除失败!', placement: 'center' })
            }
          })
          .catch(() => {
            this.$message.error({ content: '删除失败!', placement: 'center' })
          });
      }
    },
    getListData() { //获取主表格查询数据
      try {
        this.bgLoading = true
        console.log(this.popjklj);
        let obj = { ...this.queryParams, sel1: this.popobj.id };

        if (this.popjklj==='yqsbgl/sbjdjz/yqsbjd') {
          obj = { ...this.queryParams, sel_sbid: this.popobj.id };
        }
        if (this.popjklj==='yqsbgl/sbjdjz/jlqjjd') {
          obj = { ...this.queryParams, sel_jlqjid: this.popobj.id };
        }
        if (this.popjklj==='yqsbgl/sbjdjz/ylybjd') {
          obj = { ...this.queryParams, sel_ylybid: this.popobj.id };
        }
        if (this.popjklj==='yqsbgl/sbjdjz/khsbjd') {
          obj = { ...this.queryParams, sel_khsbid: this.popobj.id };
        }
        if (this.popjklj==='yqsbgl/sbjdjz/bjysbjd') {
          obj = { ...this.queryParams, sel_bjysbid: this.popobj.id };
        }
        if (this.popjklj==='yqsbgl/sbjdjz/tzsbjd') {
          obj = { ...this.queryParams, sel_tzsbid: this.popobj.id };
        }
        if (this.popjklj==='yqsbgl/sbjdjz/bzwzjd') {
          obj = { ...this.queryParams, sel_bzwzid: this.popobj.id };
        }

        this.$getListData_fj(obj, this.popjklj).then((res) => {
          if (res.success) {
            this.zbdata = res.rows;
            this.total = res.total;
          } else {
            this.zbdata = []
            this.$message.error({ content: '请重新搜索!', placement: 'center' })
          }
        })
      } catch (error) {
        this.bgLoading = false;
        console.warn('接口提示', error);
      }
    },
    doSubmit() {//处理保存按钮事件
      this.$refs['form1'].validate((valid) => {
        if (valid) {
          let obj = { ...this.formData, sbid: this.popobj.id };
           if (this.popjklj==='yqsbgl/sbjdjz/yqsbjd') {
            obj = { ...this.formData, sbid: this.popobj.id };
          }
          if (this.popjklj==='yqsbgl/sbjdjz/jlqjjd') {
            obj = { ...this.formData, jlqjid: this.popobj.id };
          }
          if (this.popjklj==='yqsbgl/sbjdjz/ylybjd') {
            obj = { ...this.formData, ylybid: this.popobj.id };
          }
          if (this.popjklj==='yqsbgl/sbjdjz/khsbjd') {
            obj = { ...this.formData, khsbid: this.popobj.id };
          }
          if (this.popjklj==='yqsbgl/sbjdjz/bjysbjd') {
            obj = { ...this.formData, bjysbid: this.popobj.id };
          }
          if (this.popjklj==='yqsbgl/sbjdjz/tzsbjd') {
            obj = { ...this.formData, tzsbid: this.popobj.id };
          }
          if (this.popjklj==='yqsbgl/sbjdjz/bzwzjd') {
            obj = { ...this.formData, bzwzid: this.popobj.id };
          }
          var _data = { ...obj };
          var _submitData = new FormData();
          for (let key in _data) {
            if (_data[key] && _data[key] instanceof Date) {
              _data[key] = dayjs(_data[key]).format('YYYY-MM-DD');
            }
            _submitData.append(key, _data[key]);
          }
          var _fileList_fj = [];
          var _fileList = [];
          if (this.hdfjwj && this.hdfjwj.uploadFiles) {
            this.hdfjwj.uploadFiles.forEach(file => {
              if (file.status == 'ready' && file.minioID) {
                _fileList_fj.push(file);
              }
            });
          }
          if (this.dgfjwj && this.dgfjwj.uploadFiles) {
            this.dgfjwj.uploadFiles.forEach(file => {
              if (file.status == 'ready' && file.minioID) {
                _fileList.push(file);
              }
            });
          }
          _submitData.append("fileList", JSON.stringify(_fileList));


          this.$submit_qt(_submitData, this.popjklj, 'jdxx')
            .then((res) => {
              if (res.success) {
                this.$message.success({ content: '保存成功!', placement: 'center' })
                this.Open1 = false;
                this.getListData()
                this.getxlsj1()
              } else {
                this.$message.error({ content: '保存失败!', placement: 'center' })
              }
            })
            .catch(() => {
              this.$message.error({ content: '保存失败!', placement: 'center' })
            });
        }
      });
    },

    doAdd(formName) {//处理新增按钮事件
      this.Open1 = true;
      this.optype = 'xz';
      this.czcxfun();
      this.formData.optype = 'add';
      this.dialogTitle = this.title + ' >> 新增';
    },
    doUpdate(row) {//处理修改按钮事件
      this.czcxfun();
      this.xzsj = row;
      this.Open1 = true;
      this.optype = 'xg';
      this.dialogTitle = this.title + ' >> 修改';
      this.formData = { ...row };
      this.formData.optype = 'update';
      // 附件查看
      const param1 = {
        start: 0,
        limit: 100,
        id: this.formData.id,
        sel_sbid: this.popobj.id,
      };
     
      this.$getListData_fj(param1, this.popjklj).then((res) => {
        if (res.success) {
          if (res.rows[0].fileid) {
            this.dgfjwj.uploadFiles = res.rows;
            this.dgfjwj.uploadFiles.forEach(file => {
              file.name = file.filename;
              file.status = 'success';
            });
          } else {
            this.dgfjwj.uploadFiles = [];
          }
        } else {
          this.dgfjwj.uploadFiles = []
          this.$message.error({ content: '请重新搜索!', placement: 'center' })
        }
      })

    },
    doDelete(row) {//处理删除按钮事件
      return this.$modal.confirm("是否确认删除该条数据？")
        .then(() => {
          this.$submit_qtsj({ id: row.id }, this.popjklj, 'jdxx/delete')
            .then((res) => {
              if (res.success) {
                this.getListData()
                this.$message.success({ content: '删除成功!', placement: 'center' })
              } else {
                this.$message.error({ content: '删除失败!', placement: 'center' })
              }
            })
            .catch(() => {
              this.$message.error({ content: '删除失败!', placement: 'center' })
            });
        })
        .catch(() => {
        });
    },
    //处理导出按钮事件
    doExportExcel() {
      var params = { ...this.queryParams };
      for (let key in params) {
        if (/^sel_/.test(key)) {
          var new_key = key.replace(/^sel_/, 'p_');
          params[new_key] = params[key];
        }
      }
      try {
        if (!this.queryParams) {
          this.$message.info({ content: '请先查询数据!', placement: 'center' })
        }
        const filename = this.title + '-' + dayjs().format('YYYYMMDDHHmmssSSS') + '.xls';
        this.$exportExcel(this.download, params, filename, this.popjklj);
      } catch (error) {
      }
    },
    doView(row) {//处理查看按钮事件
      this.Open1 = true;
      this.optype = 'ck';
      this.dialogTitle = this.title + ' >> 查看';
      this.formData = { ...row };
    },
    doViewFJ(row) {//处理查看附件按钮事件
      this.$refs.ckfj.dkfj({ start: 0, limit: 100, sel_bjysbid: row.id, }, this.popjklj);
    },
    doClose() {//处理关闭事件
      this.Open1 = false;
      this.Open2 = false;
    },
  },
})
</script>
<style lang="less" scoped>
.app-container {
  height: 100%;

  .el-table {
    overflow: scroll;
  }
}

::v-deep .el-dialog__body {
  max-height: 60vh;
  overflow-y: auto;
}

.delbutton {
  margin-right: 10px;
}

.mbBottom {
  margin-bottom: 10px;
}

.mainSearchPanel .page-header-title {
  font-size: 16px;
  color: #409EFF;
  font-weight: bolder;
  display: block;
  margin: 10px 0;
}
</style>
